"use client"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useEffect, useState, useRef } from 'react';
import axios from "axios";
import SSE from "@/lib/sse"
import MarkdownRenderer from "@/components/MarkdownRenderer"

const getUuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  })
}

const sessionId = getUuid();

export function ChatBar({ model, getUsage }) {
  const textareaRef = useRef(null);
  const [height, setHeight] = useState(25);
  const [messages, setMessages] = useState('');
  const [items, setItems] = useState([]);
  const messagesEndRef = useRef(null);

  const handleChange = (event) => {
    setMessages(event.target.value)
  }

  const clickSendMessage = () => {
    setItems((prevItems) => [...prevItems, { user: 'people', messageType: 'TEXT', message: messages }])
    sendMessage();
  }

  const handleKeyDown = (event) => {
    //handleChange({ target: { value: textareaRef.current.value } });
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault(); // 阻止默认的回车行为
      clickSendMessage();
    } else if (event.key === 'Enter' && event.shiftKey) {
      // setHeight((prevHeight) => {
      //   prevHeight.height += 25
      //   console.log(prevHeight);
      // }); // Shift+Enter时增加高度
      setHeight(height + 25)
    } else if (event.key === 'Backspace') {
      console.log(messages);
      const newLineCount = messages.split('\n').length;
      setHeight(25 * newLineCount)
    }
  };

  const sendMessage = () => {
    let sse = new SSE(`${process.env.NEXT_PUBLIC_API_URL}/api/openai/completions/stream`, {
      headers: {
        'Content-Type': 'application/json',
      },
      payload: JSON.stringify({
        "prompt": messages,
        "sessionId": sessionId,
        "model": model
      })
    })
    sse.addEventListener('open', (function () {
      setItems((prevItems) => [...prevItems, { user: 'bot', messageType: 'TEXT', message: '' }])
    }))

    sse.addEventListener('error', (function () {
      setItems((prevItems) => [...prevItems, { user: 'bot', messageType: 'TEXT', message: 'error , please login or upgrade your membership' }])
    }))

    sse.addEventListener('message', function (res) {
      let resJson = JSON.parse(res.data)
      if (resJson.code !== 0) {
        alert("error:" + resJson.msg)
        sse.close()
        getUsage()
        return
      }
      resJson = resJson.data
      if (resJson.messageType === 'TEXT') {
        if (resJson.end === true) {
          sse.close()
          getUsage()
        } else {
          setItems((prevItems) => {
            const updatedItems = [...prevItems];
            updatedItems[updatedItems.length - 1].message += resJson.message;
            return updatedItems;
          })
        }
        //图片
      } else {
        // let url_html = '';
        // resJson.message.split(",").forEach(url => {
        //   url_html += `<img class="chat-img" src="${url}"/>`
        // })
        // this_.items[this_.items.length - 1] = { user: 'bot', messageType: 'IMAGE', message: url_html }
        // sse.close()
        // this_.generating = false
      }

    }
    )

    // sse.addEventListener('error', function () {
    //   alert('server error')
    // })
    sse.stream();
    setMessages('');
    setHeight(25)
  }

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  },[items])

  return (
    // h-full overflow-hidden px-2 pt-3 sm:px-[15px]

    <div className="bg-[#f1f2f2] overflow-auto flex flex-col h-full w-full rounded-lg ">
      <header className="flex items-center justify-between p-4 bg-white border-b">
        <div className="flex items-center space-x-2">
          <Disc3Icon className="w-6 h-6" />
          <span className="text-lg font-semibold">{model}</span>
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-sm text-gray-500">Search</span>
          <Switch id="search" />
        </div>
      </header>
      <main className="flex-1 p-4 overflow-y-auto w-full">
        {items.map((item, index) => (
          // className="bg-[#fdf6e5] mt-4 w-10/12 flex items-start space-x-2 rounded-lg ${item.user === 'bot' ? 'justify-start' : 'justify-end'}"
          <div key={index} className={`w-4/5 p-4 mt-8 overflow-auto  items-start rounded-lg my-2 ${item.user === 'bot' ? 'bg-[#fdf6e5]' : ' text-right ml-auto bg-[#b9d7f3]'} `}>
            <MarkdownRenderer content={item.message} />
          </div>
        ))}

        <div ref={messagesEndRef} />
      </main>
      <footer className="flex items-center p-4 bg-white border-t">
        <ActivityIcon className="w-6 h-6 text-gray-500" />
        {/* <Input type="text" placeholder="使用Shift+Enter换行" className="flex-1 mx-2 border-none focus:ring-0" /> */}
        <textarea ref={textareaRef} onKeyDown={handleKeyDown} onChange={handleChange} value={messages} placeholder="use Shift+Enter wrap a line" className="flex-1 mx-2 border-none focus:ring-0" style={{ height: `${height}px`, width: '100%' }}></textarea>
        <Button onClick={clickSendMessage} className="bg-[#bce5b6] text-white">Send</Button>
      </footer>
    </div>

  )
}

function ActivityIcon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />
    </svg>
  )
}


function Disc3Icon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
      <path d="M6 12c0-1.7.7-3.2 1.8-4.2" />
      <circle cx="12" cy="12" r="2" />
      <path d="M18 12c0 1.7-.7 3.2-1.8 4.2" />
    </svg>
  )
}


function XIcon(props) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M18 6 6 18" />
      <path d="m6 6 12 12" />
    </svg>
  )
}
